/**
 * 杂物查询指令实现
 * 功能：实现WebSocket指令1265，查询杂物物品
 */

const mysql = require('mysql2/promise');
const fs = require('fs');
const path = require('path');

// 数据库连接配置（硬编码）
const DB_CONFIG = {
    host: '43.143.253.188',
    port: 3306,
    user: 'nextjs',
    password: 'yEAiRE2jcxTyRBy5',
    database: 'nextjs',
    charset: 'utf8mb4'
};

class MiscItemsQueryService {
    constructor() {
        this.connection = null;
    }

    // 连接数据库
    async connectDatabase() {
        try {
            console.log('🔌 正在连接数据库...');
            this.connection = await mysql.createConnection(DB_CONFIG);
            console.log('✅ 数据库连接成功');
        } catch (error) {
            console.error('❌ 数据库连接失败:', error.message);
            throw error;
        }
    }

    // 关闭数据库连接
    async closeDatabase() {
        if (this.connection) {
            await this.connection.end();
            console.log('🔌 数据库连接已关闭');
        }
    }

    // 定义杂物物品ID数组
    getMiscItemIds() {
        return {
            // t=3: 杂物类
            3: [71, 72, 74, 75, 108, 109],
            // t=2: 矿物类
            2: [58, 38, 48, 39, 49, 59, 60, 50, 40, 61, 41, 51, 62, 42, 52, 63, 53, 43, 54, 44, 64, 55, 45, 65, 56, 46, 66, 57, 47, 67]
        };
    }

    // 查询杂物物品数据
    async queryMiscItems(type, pageNum = 0) {
        try {
            const itemIds = this.getMiscItemIds()[type];
            if (!itemIds || itemIds.length === 0) {
                return {
                    act_id: 1265,
                    code: 0,
                    list: []
                };
            }

            // 构建查询SQL
            const placeholders = itemIds.map(() => '?').join(',');
            const sql = `
                SELECT 
                    id,
                    name,
                    pic,
                    silver_price as price
                FROM basic_items 
                WHERE id IN (${placeholders})
                ORDER BY id
            `;

            console.log(`🔍 查询类型 ${type} 的杂物物品，ID列表: [${itemIds.join(', ')}]`);

            const [rows] = await this.connection.execute(sql, itemIds);

            // 转换为标准格式
            const list = rows.map(row => ({
                id: row.id,
                name: row.name,
                pic: row.pic || 'none.png',
                price: row.price
            }));

            console.log(`✅ 查询到 ${list.length} 个物品`);

            return {
                act_id: 1265,
                code: 0,
                list: list
            };

        } catch (error) {
            console.error('❌ 查询杂物物品失败:', error.message);
            return {
                act_id: 1265,
                code: -1,
                message: '查询失败',
                list: []
            };
        }
    }

    // 检查并修正数据库中的价格数据
    async checkAndFixPrices() {
        try {
            console.log('🔍 检查数据库中的价格数据...');

            const itemIds = this.getMiscItemIds();
            const allIds = [...itemIds[2], ...itemIds[3]];

            const placeholders = allIds.map(() => '?').join(',');
            const sql = `
                SELECT 
                    id,
                    name,
                    silver_price,
                    pic
                FROM basic_items 
                WHERE id IN (${placeholders})
                ORDER BY id
            `;

            const [rows] = await this.connection.execute(sql, allIds);

            console.log(`\n📊 当前数据库中的价格数据:`);
            console.log('=' * 80);

            for (const row of rows) {
                console.log(`ID: ${row.id}, 名称: ${row.name}, 银币价格: ${row.silver_price}, 图片: ${row.pic || 'none.png'}`);
            }

            // 根据标准数据修正价格
            const standardPrices = {
                // 杂物类 (t=3)
                71: { name: '鲜花', price: 300, pic: 'xh.png' },
                72: { name: '酒菜', price: 300, pic: 'jc.png' },
                74: { name: '路书', price: 750, pic: 'ls.png' },
                75: { name: '香案', price: 7500, pic: 'xa.png' },
                108: { name: '大包裹', price: 22500, pic: 'dbg.png' },
                109: { name: '小包裹', price: 9000, pic: 'xbg.png' },

                // 矿物类 (t=2)
                58: { name: '1级金矿', price: 1500, pic: 'none.png' },
                38: { name: '1级铁矿', price: 1500, pic: 'none.png' },
                48: { name: '1级银矿', price: 1500, pic: 'none.png' },
                39: { name: '2级铁矿', price: 3000, pic: 'none.png' },
                49: { name: '2级银矿', price: 3000, pic: 'none.png' },
                59: { name: '2级金矿', price: 3000, pic: 'none.png' },
                60: { name: '3级金矿', price: 6000, pic: 'none.png' },
                50: { name: '3级银矿', price: 6000, pic: 'none.png' },
                40: { name: '3级铁矿', price: 6000, pic: 'none.png' },
                61: { name: '4级金矿', price: 15000, pic: 'none.png' },
                41: { name: '4级铁矿', price: 15000, pic: 'none.png' },
                51: { name: '4级银矿', price: 15000, pic: 'none.png' },
                62: { name: '5级金矿', price: 30000, pic: 'none.png' },
                42: { name: '5级铁矿', price: 30000, pic: 'none.png' },
                52: { name: '5级银矿', price: 30000, pic: 'none.png' },
                63: { name: '6级金矿', price: 60000, pic: 'none.png' },
                53: { name: '6级银矿', price: 60000, pic: 'none.png' },
                43: { name: '6级铁矿', price: 60000, pic: 'none.png' },
                54: { name: '7级银矿', price: 120000, pic: 'none.png' },
                44: { name: '7级铁矿', price: 120000, pic: 'none.png' },
                64: { name: '7级金矿', price: 120000, pic: 'none.png' },
                55: { name: '8级银矿', price: 240000, pic: 'none.png' },
                45: { name: '8级铁矿', price: 240000, pic: 'none.png' },
                65: { name: '8级金矿', price: 240000, pic: 'none.png' },
                56: { name: '9级银矿', price: 480000, pic: 'none.png' },
                46: { name: '9级铁矿', price: 480000, pic: 'none.png' },
                66: { name: '9级金矿', price: 480000, pic: 'none.png' },
                57: { name: '10级银矿', price: 960000, pic: 'none.png' },
                47: { name: '10级铁矿', price: 960000, pic: 'none.png' },
                67: { name: '10级金矿', price: 960000, pic: 'none.png' }
            };

            console.log(`\n🔧 开始修正数据库数据...`);
            console.log('=' * 80);

            let updateCount = 0;

            for (const row of rows) {
                const standard = standardPrices[row.id];
                if (standard) {
                    const needsUpdate =
                        row.silver_price !== standard.price ||
                        row.pic !== standard.pic ||
                        row.name !== standard.name;

                    if (needsUpdate) {
                        console.log(`\n🔄 更新物品 ID ${row.id}:`);
                        console.log(`   名称: "${row.name}" → "${standard.name}"`);
                        console.log(`   银币价格: ${row.silver_price} → ${standard.price}`);
                        console.log(`   图片: "${row.pic || 'none.png'}" → "${standard.pic}"`);

                        await this.connection.execute(`
                            UPDATE basic_items 
                            SET name = ?, silver_price = ?, pic = ?
                            WHERE id = ?
                        `, [standard.name, standard.price, standard.pic, row.id]);

                        updateCount++;
                        console.log(`   ✅ 更新成功`);
                    } else {
                        console.log(`✅ 物品 ID ${row.id} 数据已正确`);
                    }
                }
            }

            console.log(`\n📊 修正完成，共更新了 ${updateCount} 个物品`);

        } catch (error) {
            console.error('❌ 检查修正价格数据失败:', error.message);
        }
    }

    // 测试查询功能
    async testQuery() {
        try {
            console.log('\n🧪 测试查询功能...');
            console.log('=' * 60);

            // 测试 t=3 (杂物类)
            console.log('\n📋 测试 t=3 (杂物类):');
            const result3 = await this.queryMiscItems(3, 0);
            console.log('请求参数:', JSON.stringify({ c: 1265, d: { t: 3, pageNum: 0 } }, null, 2));
            console.log('返回结果:', JSON.stringify(result3, null, 2));

            // 测试 t=2 (矿物类)
            console.log('\n📋 测试 t=2 (矿物类):');
            const result2 = await this.queryMiscItems(2, 0);
            console.log('请求参数:', JSON.stringify({ c: 1265, d: { t: 2, pageNum: 0 } }, null, 2));
            console.log('返回结果:', JSON.stringify(result2, null, 2));

        } catch (error) {
            console.error('❌ 测试查询失败:', error.message);
        }
    }

    // 运行完整流程
    async run() {
        console.log('🚀 开始杂物查询指令实现...\n');

        try {
            // 1. 连接数据库
            await this.connectDatabase();

            // 2. 检查并修正数据库数据
            await this.checkAndFixPrices();

            // 3. 测试查询功能
            await this.testQuery();

            console.log('\n🎉 杂物查询指令实现完成！');

        } catch (error) {
            console.error('💥 实现流程失败:', error.message);
            throw error;
        } finally {
            // 4. 关闭数据库连接
            await this.closeDatabase();
        }
    }
}

// 运行实现
async function main() {
    console.log('🎯 杂物查询指令实现工具');
    console.log('   目标：实现WebSocket指令1265，确保数据一致性\n');

    const service = new MiscItemsQueryService();
    await service.run();
}

// 如果直接运行此脚本
if (require.main === module) {
    main().catch((error) => {
        console.error('💥 脚本执行失败:', error.message);
        process.exit(1);
    });
}

module.exports = MiscItemsQueryService;
